/*
Copyright (C) 2010- Peter Bui and Aaron Dingler.
This software is distributed under the GNU General Public License.
See the file COPYING for details.
*/

#include "smq_catalog.h"
#include "smq_common.h"

#include <debug.h>
#include <link.h>
#include <list.h>
#include <catalog_query.h>
#include <catalog_server.h>
#include <domain_name_cache.h>
#include <stringtools.h>
#include <xmalloc.h>

#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>

static int SMQ_Catalog_Stalled_Timeout = SMQ_CLIENT_DEFAULT_STALLED_TIMEOUT;

struct list *
smq_catalog_get_hosts(char *name, int check_queue)
{
    struct catalog_query *cq;
    struct nvpair *nv;
    struct list *hl;
    struct smq_catalog_host *h;
    
    int i;
    char host[SMQ_LINE_MAX];
    char temp[SMQ_LINE_MAX];
    char fqns[DOMAIN_NAME_MAX];

    if ((i = strpos(name, ':')) >= 0) {
	strncpy(host, name, i);
	host[i] = 0;
	strncpy(temp, &name[i + 1], SMQ_LINE_MAX);
	strncpy(name, temp, SMQ_LINE_MAX);
    } else {
        host[0] = 0;
    }

    domain_name_cache_guess(fqns);

    debug(D_DEBUG, "catalog query(host, name): %s, %s", host, name);

    hl = list_create();
    cq = catalog_query_create(CATALOG_HOST, CATALOG_PORT, time(0) + SMQ_Catalog_Stalled_Timeout);

    while ((nv = catalog_query_read(cq, time(0) + SMQ_Catalog_Stalled_Timeout))) {
        if (strcmp(nvpair_lookup_string(nv, "type"), "smq") == 0) {
	    if (check_queue && strcmp(nvpair_lookup_string(nv, "smq_queue"), name) != 0) {
		nvpair_delete(nv);
		continue;
	    }
            if (host[0] && strcmp(nvpair_lookup_string(nv, "name"), host) != 0) {
		nvpair_delete(nv);
		continue;
	    }

	    h = xxmalloc(sizeof(struct smq_catalog_host));
	    strncpy(h->address, nvpair_lookup_string(nv, "address"), SMQ_ADDRESS_MAX);
	    h->port = nvpair_lookup_integer(nv, "smq_port");

	    debug(D_DEBUG, "queue %s host found: %s:%d", name, h->address, h->port);

	    if (strstr(nvpair_lookup_string(nv, "name"), fqns))
		list_push_head(hl, h);
	    else
		list_push_tail(hl, h);
        }
        nvpair_delete(nv);
    }

    return hl;
}

/* 
vim: sw=4 sts=4 ts=8 ft=cpp
*/
